const AIService = require('../services/aiService');
const Conversation = require('../models/Conversation');

// AI对话控制器
exports.sendMessage = async (req, res) => {
  try {
    // 获取用户输入和对话ID
    const { message, conversationId } = req.body;
    const userId = req.user.id;
    
    // 验证必要参数
    if (!message) {
      return res.status(400).json({ message: '消息内容不能为空' });
    }
    
    let currentConversationId = conversationId;
    let history = [];
    
    // 如果没有会话ID，创建新会话
    if (!currentConversationId) {
      const newConversation = await Conversation.create({
        user_id: userId,
        title: message.substring(0, 30) + (message.length > 30 ? '...' : '')
      });
      currentConversationId = newConversation.id;
    } else {
      // 获取历史消息
      const messages = await Conversation.getConversationMessages(currentConversationId);
      
      // 限制历史消息数量（防止超过API限制）
      const limitedMessages = messages.slice(-10);
      
      // 转换为AI服务需要的格式
      history = limitedMessages.map(msg => ({
        role: msg.role,
        content: msg.content
      }));
    }
    
    // 保存用户消息
    await Conversation.saveMessage({
      conversation_id: currentConversationId,
      role: 'user',
      content: message
    });
    
    // 调用AI服务获取回复
    const response = await AIService.sendMessage(message, history);
    
    // 保存AI回复
    await Conversation.saveMessage({
      conversation_id: currentConversationId,
      role: 'assistant',
      content: response.reply
    });
    
    // 返回响应
    res.json({
      success: true,
      data: {
        reply: response.reply,
        conversationId: currentConversationId
      }
    });
  } catch (error) {
    console.error('AI对话错误:', error.message);
    res.status(500).json({
      success: false,
      message: '处理您的请求时出错',
      error: process.env.NODE_ENV === 'development' ? error.message : undefined
    });
  }
};

// 获取用户的所有对话
exports.getUserConversations = async (req, res) => {
  try {
    const userId = req.user.id;
    const conversations = await Conversation.getUserConversations(userId);
    
    res.json({
      success: true,
      data: conversations
    });
  } catch (error) {
    console.error('获取对话列表错误:', error.message);
    res.status(500).json({
      success: false,
      message: '获取对话列表失败'
    });
  }
};

// 获取对话的消息
exports.getConversationMessages = async (req, res) => {
  try {
    const { id } = req.params;
    const messages = await Conversation.getConversationMessages(id);
    
    res.json({
      success: true,
      data: messages
    });
  } catch (error) {
    console.error('获取对话消息错误:', error.message);
    res.status(500).json({
      success: false,
      message: '获取对话消息失败'
    });
  }
};

// 删除对话
exports.deleteConversation = async (req, res) => {
  try {
    const { id } = req.params;
    const result = await Conversation.delete(id);
    
    if (result) {
      res.json({
        success: true,
        message: '对话已删除'
      });
    } else {
      res.status(404).json({
        success: false,
        message: '对话不存在或已删除'
      });
    }
  } catch (error) {
    console.error('删除对话错误:', error.message);
    res.status(500).json({
      success: false,
      message: '删除对话失败'
    });
  }
};

// 更新对话标题
exports.updateConversationTitle = async (req, res) => {
  try {
    const { id } = req.params;
    const { title } = req.body;
    
    if (!title) {
      return res.status(400).json({
        success: false,
        message: '标题不能为空'
      });
    }
    
    const result = await Conversation.updateTitle(id, title);
    
    if (result) {
      res.json({
        success: true,
        message: '标题已更新'
      });
    } else {
      res.status(404).json({
        success: false,
        message: '对话不存在'
      });
    }
  } catch (error) {
    console.error('更新对话标题错误:', error.message);
    res.status(500).json({
      success: false,
      message: '更新对话标题失败'
    });
  }
}; 